﻿$(function () {
    helper.GetRoleDb(function(data) {
        AllRoleDB = data;
        RefreshUser();
    });
    
    //Init User & Role Tab
    $("#tabs_div").tabs({
        select: function (event, ui) {
            var tabname = ui.panel.id;
            switch (tabname) {
            
                case 'tabUserManagerTab': RefreshUser(); break;
                case 'tabRoleManagerTab': RefreshRole(); break;
            }
            return true;
        }
    });

    //Init Add new user dialog
    $("#dialog:ui-dialog").dialog("destroy");
    $("#dialog-form").dialog({
        autoOpen: false,
        height: 450,
        dialogClass: "addUserDialog",    
        width: 350,
        modal: true,
        title: "Create an account",
        buttons: {
            "Create an account": function () {
                var bValid = true;
                updateTips("");
                allFields.removeClass("ui-state-error");
               
                bValid = bValid && checkLength(name, "username", 3, 16);
                var role = $('#SelectRole option:selected').val();
                if (role === "sale") {
                    bValid = bValid && checkLengthSaleGrp($('#msalegrp').val()).valid;
                }

                //bValid = bValid && checkLength($('#msalegrp'), "msalegrp", 1, 3);
                //                        bValid = bValid && checkLength(email, "email", 6, 80);
                //                        bValid = bValid && checkLength(password, "password", 5, 16);

                //                        bValid = bValid && checkRegexp(name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter.");
                //                        // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                //                        bValid = bValid && checkRegexp(email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com");
                //                        bValid = bValid && checkRegexp(password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9");
                var newUser = {UserName: name.val(),
                    RoleName: role,
                    msalegrp: $('#msalegrp').val(),
                    Tel: $('#txttel').val(),
                    Fax: $('#txtfax').val(),
                    Password: $('#password').val()};
                
                if (bValid) {
                    helper.AddUserDb(newUser, function () {
                        MsgBox('Create user completed');
                        RefreshUser();
                        $("#dialog-form").dialog("close");
                    });
                }
                
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        },
        close: function () {
            allFields.val("").removeClass("ui-state-error");
        }
    });
    $("#dialog-addRole").dialog({
        autoOpen: false,
        height: 250,
        width: 350,
        dialogClass: "addRoleDialog",   
        modal: true,
        title: "Create a role",
        buttons: {
            "Create a role": function () {
                var bValid = true;
                allFields.removeClass("ui-state-error");
                var rolename = $("#rolenametxt");
                var roledescript = $("#roleDescripttxt");
                var roledisable = $("#isroleDisable");
               
                var newrole = {RoleName: rolename.val(),
                    RoleDescription: roledescript.val(),
                    IsDisable: roledisable.is(':checked')};
               
                //bValid = bValid && checkLength(rolename.val(), "rolename", 3, 16);
                if (bValid) {
                    
                    helper.AddRoleDb(newrole, function () {
                        MsgBox('Create role completed');
                        RefreshRole();
                        FormRoleClear();
                        $("#dialog-addRole").dialog("close");
                    });
                }
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        },
        close: function () {
            allFields.val("").removeClass("ui-state-error");
        }
    });
    //Init button
            $("#menuAddUser")
			.button({
                 
                icons: {
                    primary: "ui-icon-plusthick"
                },
            })
			.click(function () {
			    $("#dialog-form").dialog("open");
			    updateTips('');
                $("#msalegrp").removeClass("ui-state-error");
			    var top = ($(window).height() - 450) / 2;
	            var left = ($(window).width() - 350) / 2;

	            $(".addUserDialog").css('left', left);
	            $(".addUserDialog").css('top', top);
			    bindRoleDropdown();
			});

            $("#menuDeleteUser")
			.button({
                 
                icons: {
                    primary: "ui-icon-minusthick"
                },
            })
			.click(function () {
			    var selectedConthIndexes = grid.getSelectedRows();
			    var top = ($(window).height() - 250) / 2;
			    var left = ($(window).width() - 350) / 2;
			    if (selectedConthIndexes.length < 1) {
			        $("#dialog-message").dialog("open");
			        $(".Dialog").css('left', left);
			        $(".Dialog").css('top', top);
			    }
			    else {
			        $("#dialog-confirm").dialog("open");
			        $(".Dialog").css('left', left);
			        $(".Dialog").css('top', top);
			    }


			});

            $("#menuAddUserRole")
			.button({
                 
                icons: {
                    primary: "ui-icon-plusthick"
                },
            })
			.click(function () {
			    $("#dialog-addRole").dialog("open");
			    var top = ($(window).height() - 140) / 2;
	            var left = ($(window).width() - 350) / 2;

	            $(".addRoleDialog").css('left', left);
	            $(".addRoleDialog").css('top', top);
			});
    

            $("#menuDeleteUserRole")
			.button({
                 
                icons: {
                    primary: "ui-icon-minusthick"
                },
            })
			.click(function () {
			    var selectedConthIndexes = gridRole.getSelectedRows();
			    var top = ($(window).height() - 250) / 2;
			    var left = ($(window).width() - 350) / 2;
			    if (selectedConthIndexes.length < 1) {
			        $("#dialog-message").dialog("open");
			        $(".Dialog").css('left', left);
			        $(".Dialog").css('top', top);
			    }
			    else {
			        $("#dialog-confirmDeleteRole").dialog("open");
			        $(".Dialog").css('left', left);
			        $(".Dialog").css('top', top);
			    }
			    
                
			    
			});
    
            $("#btnUserLookup")
			.button({

                icons: {
                    primary: "ui-icon-search"
                },
            })
			.click(function () {
			    var user = $('#name').val();
			    helper.CheckADuser(user, function(data) {
                    if(data) {
                        $('#email').val(data.Email);
                        $('#password').val('123456');
                    }
			    });
			    
                
			    
			});
            
    
    
    $("#dialog-confirm" ).dialog({
            autoOpen: false,
			resizable: false,
			height:150,
            dialogClass: "Dialog",
			modal: true,
			buttons: {
				"Delete seleted items": function() {
				    var selectedIndexes = grid.getSelectedRows();
                    var selectedUser = [];
                    jQuery.each(selectedIndexes, function (index, value) {
                        selectedUser.push(grid.getData()[value]["UserName"]);
                    });
                    deleteUser(selectedUser);
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			}
		});
    
     $("#dialog-confirmDeleteRole" ).dialog({
            autoOpen: false,
			resizable: false,
			height:150,
            dialogClass: "Dialog",
			modal: true,
			buttons: {
				"Delete seleted items": function() {
				    var selectedIndexes = gridRole.getSelectedRows();
                    var selectedRole = [];
                    jQuery.each(selectedIndexes, function (index, value) {
                        selectedRole.push(gridRole.getData()[value]["RoleName"]);
                    });
                    deleteRole(selectedRole);
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			}
		});
     $("#dialog-message" ).dialog({
            autoOpen: false,
			resizable: false,
			height:120,
            dialogClass: "Dialog",
			modal: true,
			buttons: {
				Ok: function() {
					$( this ).dialog( "close" );
				}
			}
		});
    
    // Event on load
    
    
})